﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NLog;
using OddUserManager.Model;
using OddUserManager.Service.IServices;
using OddUserManager.Web.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace OddUserManager.Web.Controllers
{
    [AllowAnonymous]
    public class LoginController : Controller
    {
        static Logger log = LogManager.GetCurrentClassLogger();
        private IAppUserService _userAppService;
        private IMenusService _menusService;

        public LoginController(IAppUserService userAppService, IMenusService menusService)
        {
            _menusService = menusService;
            _userAppService = userAppService;
        }


        // GET: /<controller>/
        public IActionResult Index(string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }


        public async Task<IActionResult> GetCurrentUserMenus()
        {

            JsonData d = new JsonData();
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            if (result.Succeeded)
            {
                var Id = result.Principal.Identity.Name;

                d.Data = _menusService.GetMenusByUserId(int.Parse(Id)).Where(p => p.Type == 0).ToList();
                
            }
            else {
                d.Data = null;
            }
            return Json(d);
        }


        public async Task<JsonResult> GetCurrentUser()
        {
            JsonData d = new JsonData();
            AppUser user = null;
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            if (result.Succeeded)
            {
                var Id = result.Principal.Identity.Name;
                user = _userAppService.GetUserById(int.Parse(Id));
                user.UPassword = "*********";
                d.Data = user;
            }
            else
            {
                d.Data = null;
            }
            return Json(d);
        }


        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Index(LoginModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;

            if (ModelState.IsValid)
            {
                var user = _userAppService.CheckUser(model.UserName, model.Password);
                //检查用户信息
                if (null != user)
                {
                    var claimsUser = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme));

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsUser,
                          new AuthenticationProperties
                          {
                              ExpiresUtc = DateTime.UtcNow.AddHours(12),
                              IsPersistent = true,
                              AllowRefresh = false
                          });

                    //user.LastLoginTime = DateTime.Now;
                    user.LoginTimes += 1;
                    _userAppService.UpdateLoginTime(user.Id, DateTime.Now, user.LoginTimes);

                    //await Task.Run(() => { Thread.Sleep(10000);return "测试"; });

                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        return Redirect(returnUrl);
                    }
                }
                ViewBag.ErrorInfo = "用户名或密码错误。";
                return View();
            }
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                    break;
                }
            }
            return View(model);
        }


        public async Task<IActionResult> SignOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Index", "Login");
        }
    }
}
